home *** CD-ROM | disk | FTP | other *** search
/ Freaks Macintosh Archive / Freaks Macintosh Archive.bin / Freaks Macintosh Archives / Textfiles / zines / Phrack / Phrack Issue 53.sit / 53 / P53-15 < prev   
Text File  |  1998-07-08  |  11KB  |  411 lines

  1. ---[  Phrack Magazine   Volume 8, Issue 53 July 8, 1998, article 15 of 15
  2.  
  3.  
  4. -------------------------[  Phrack Magzine Extraction Utility
  5.  
  6.  
  7. --------[  Phrack Staff
  8.  
  9.  
  10.     Neat0!  A python version!  Thanks to  Timmy 2tone <_spoon_@usa.net>.
  11. By all means, keep sending new versions on in.
  12.  
  13.  
  14.  
  15. ---------------------8<------------CUT-HERE----------->8---------------------
  16.  
  17. <++> EX/PMEU/extract2.c
  18. /*  extract.c by Phrack Staff and sirsyko 
  19.  *
  20.  *  (c) Phrack Magazine, 1997 
  21.  *      1.8.98 rewritten by route:
  22.  *          - aesthetics
  23.  *          - now accepts file globs
  24.  *      todo:
  25.  *          - more info in tag header (file mode, checksum)
  26.  *  Extracts textfiles from a specially tagged flatfile into a hierarchical 
  27.  *  directory strcuture.  Use to extract source code from any of the articles 
  28.  *  in Phrack Magazine (first appeared in Phrack 50).
  29.  *
  30.  *  gcc -o extract extract.c
  31.  *  
  32.  *  ./extract file1 file2 file3 ...
  33.  */
  34.  
  35.  
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <sys/stat.h>
  39. #include <string.h>
  40. #include <dirent.h>
  41.  
  42. #define BEGIN_TAG   "<++> "
  43. #define END_TAG     "<-->"
  44. #define BT_SIZE     strlen(BEGIN_TAG)
  45. #define ET_SIZE     strlen(END_TAG)
  46.  
  47. struct f_name
  48. {
  49.     u_char name[256];
  50.     struct f_name *next;
  51. };
  52.  
  53. int
  54. main(int argc, char **argv)
  55.     u_char b[256], *bp, *fn;
  56.     int i, j = 0;
  57.     FILE *in_p, *out_p = NULL; 
  58.     struct f_name *fn_p = NULL, *head = NULL; 
  59.  
  60.     if (argc < 2)
  61.     {
  62.         printf("Usage: %s file1 file2 ... filen\n", argv[0]);
  63.         exit(0); 
  64.     }
  65.  
  66.     /*
  67.      *  Fill the f_name list with all the files on the commandline (ignoring
  68.      *  argv[0] which is this executable).  This includes globs.
  69.      */
  70.     for (i = 1; (fn = argv[i++]); )
  71.     {
  72.         if (!head)
  73.         {
  74.             if (!(head = (struct f_name *)malloc(sizeof(struct f_name))))
  75.             {
  76.                 perror("malloc");
  77.                 exit(1);
  78.             }
  79.             strncpy(head->name, fn, sizeof(head->name));
  80.             head->next = NULL;
  81.             fn_p = head;
  82.         }
  83.         else
  84.         {
  85.             if (!(fn_p->next = (struct f_name *)malloc(sizeof(struct f_name))))
  86.             {
  87.                 perror("malloc");
  88.                 exit(1);
  89.             }
  90.             fn_p = fn_p->next;
  91.             strncpy(fn_p->name, fn, sizeof(fn_p->name));
  92.             fn_p->next = NULL;
  93.         }
  94.     }
  95.     /*
  96.      *  Sentry node.
  97.      */
  98.     if (!(fn_p->next = (struct f_name *)malloc(sizeof(struct f_name))))
  99.     {
  100.         perror("malloc");
  101.         exit(1);
  102.      }
  103.     fn_p = fn_p->next;
  104.     fn_p->next = NULL;
  105.  
  106.     /*
  107.      *  Check each file in the f_name list for extraction tags.
  108.      */
  109.     for (fn_p = head; fn_p->next; fn_p = fn_p->next)
  110.     {
  111.         if (!(in_p = fopen(fn_p->name, "r")))
  112.         {
  113.             fprintf(stderr, "Could not open input file %s.\n", fn_p->name);
  114.         continue;
  115.         }
  116.         else fprintf(stderr, "Opened %s\n", fn_p->name);
  117.         while (fgets(b, 256, in_p))
  118.         { 
  119.             if (!strncmp (b, BEGIN_TAG, BT_SIZE))
  120.             { 
  121.             b[strlen(b) - 1] = 0;           /* Now we have a string. */
  122.                 j++;
  123.  
  124.                 if ((bp = strchr(b + BT_SIZE + 1, '/')))
  125.                 {
  126.                     while (bp)
  127.                     {
  128.                 *bp = 0;
  129.                 mkdir(b + BT_SIZE, 0700); 
  130.                 *bp = '/';
  131.                 bp = strchr(bp + 1, '/'); 
  132.             }
  133.                 }
  134.                 if ((out_p = fopen(b + BT_SIZE, "w")))
  135.                 {
  136.                     printf("- Extracting %s\n", b + BT_SIZE);
  137.                 }
  138.                 else
  139.                 {
  140.             printf("Could not extract '%s'.\n", b + BT_SIZE);
  141.             continue;
  142.             }
  143.         } 
  144.             else if (!strncmp (b, END_TAG, ET_SIZE))
  145.             {
  146.             if (out_p) fclose(out_p);
  147.             else
  148.                 {
  149.                 fprintf(stderr, "Error closing file %s.\n", fn_p->name);
  150.             continue;
  151.             }
  152.             } 
  153.             else if (out_p)
  154.             {
  155.                 fputs(b, out_p);
  156.             }
  157.         }
  158.     }
  159.     if (!j) printf("No extraction tags found in list.\n");
  160.     else printf("Extracted %d file(s).\n", j);
  161.     return (0);
  162. }
  163.  
  164. /* EOF */
  165. <-->
  166. <++> EX/PMEU/extract.pl
  167. # Daos <daos@nym.alias.net>
  168. #!/bin/sh -- # -*- perl -*- -n
  169. eval 'exec perl $0 -S ${1+"$@"}' if 0;
  170.  
  171. $opening=0;
  172.  
  173. if (/^\<\+\+\>/) {$curfile = substr($_ , 5); $opening=1;};
  174. if (/^\<\-\-\>/) {close ct_ex; $opened=0;}; 
  175. if ($opening) {                        
  176.         chop $curfile;                 
  177.         $sex_dir= substr( $curfile, 0, ((rindex($curfile,'/'))) ) if ($curfile =~ m/\//);
  178.         eval {mkdir $sex_dir, "0777";}; 
  179.         open(ct_ex,">$curfile"); 
  180.         print "Attempting extraction of $curfile\n";
  181.         $opened=1; 
  182. }
  183. if ($opened && !$opening) {print ct_ex $_}; 
  184. <-->
  185.  
  186. <++> EX/PMEU/extract.awk
  187. #!/usr/bin/awk -f
  188. #
  189. # Yet Another Extraction Script
  190. # - <sirsyko>
  191. #
  192. /^\<\+\+\>/ {
  193.         ind = 1
  194.         File = $2
  195.         split ($2, dirs, "/")
  196.         Dir="."
  197.         while ( dirs[ind+1] ) {
  198.                 Dir=Dir"/"dirs[ind]
  199.                 system ("mkdir " Dir" 2>/dev/null")
  200.                 ++ind
  201.         }
  202.         next
  203. }
  204. /^\<\-\-\>/ {
  205.         File = ""
  206.         next
  207. }
  208. File { print >> File }
  209. <-->
  210. <++> EX/PMEU/extract.sh
  211. #!/bin/sh
  212. # exctract.sh : Written 9/2/1997 for the Phrack Staff by <sirsyko>
  213. #
  214. # note, this file will create all directories relative to the current directory
  215. # originally a bug, I've now upgraded it to a feature since I dont want to deal
  216. # with the leading / (besides, you dont want hackers giving you full pathnames
  217. # anyway, now do you :)
  218. # Hopefully this will demonstrate another useful aspect of IFS other than 
  219. # haxoring rewt
  220. #
  221. # Usage: ./extract.sh <filename>
  222.  
  223. cat $* | (
  224. Working=1
  225. while [ $Working ];
  226. do
  227.         OLDIFS1="$IFS"
  228.         IFS=
  229.         if read Line; then
  230.                 IFS="$OLDIFS1"
  231.                 set -- $Line
  232.                 case "$1" in
  233.                 "<++>") OLDIFS2="$IFS"
  234.                         IFS=/
  235.                         set -- $2
  236.                         IFS="$OLDIFS2"
  237.                         while [ $# -gt 1 ]; do
  238.                                 File=${File:-"."}/$1
  239.                                 if [ ! -d $File ]; then
  240.                                         echo "Making dir $File"
  241.                                         mkdir $File
  242.                                 fi
  243.                                 shift
  244.                         done                               
  245.                         File=${File:-"."}/$1
  246.                         echo "Storing data in $File"
  247.                 ;;
  248.                 "<-->") if [ "x$File" != "x" ]; then
  249.                                 unset File
  250.                         fi ;;
  251.                 *)      if [ "x$File" != "x" ]; then
  252.                                         IFS=
  253.                                         echo "$Line" >> $File
  254.                                         IFS="$OLDIFS1"
  255.                         fi
  256.                 ;;
  257.                 esac
  258.                 IFS="$OLDIFS1"
  259.         else
  260.                 echo "End of file"
  261.                 unset Working
  262.         fi
  263. done
  264. )                                                                    
  265. <-->
  266. <++> EX/PMEU/extract.py
  267. #! /bin/env python
  268. # extract.py    Timmy 2tone <_spoon_@usa.net>
  269.  
  270. import sys, string, getopt, os
  271.  
  272. class Datasink:
  273.     """Looks like a file, but doesn't do anything."""
  274.     def write(self, data): pass
  275.     def close(self): pass
  276.  
  277. def extract(input, verbose = 1):
  278.     """Read a file from input until we find the end token."""
  279.  
  280.     if type(input) == type('string'):
  281.         fname = input
  282.         try: input = open(fname)
  283.         except IOError, (errno, why):
  284.             print "Can't open %s: %s" % (fname, why)
  285.             return errno
  286.     else:
  287.         fname = '<file descriptor %d>' % input.fileno()
  288.  
  289.     inside_embedded_file = 0
  290.     linecount = 0
  291.     line = input.readline()
  292.     while line:
  293.  
  294.         if not inside_embedded_file and line[:4] == '<++>':
  295.  
  296.             inside_embedded_file = 1
  297.             linecount = 0
  298.  
  299.             filename = string.strip(line[4:])
  300.             if mkdirs_if_any(filename) != 0:
  301.                 pass
  302.  
  303.             try: output = open(filename, 'w')
  304.             except IOError, (errno, why):
  305.                 print "Can't open %s: %s; skipping file" % (filename, why)
  306.                 output = Datasink()
  307.                 continue
  308.  
  309.             if verbose:
  310.                 print 'Extracting embedded file %s from %s...' % (filename,
  311.                                                                   fname),
  312.  
  313.         elif inside_embedded_file and line[:4] == '<-->':
  314.             output.close()
  315.             inside_embedded_file = 0
  316.             if verbose and not isinstance(output, Datasink):
  317.                 print '[%d lines]' % linecount
  318.  
  319.         elif inside_embedded_file:
  320.             output.write(line)
  321.  
  322.         # Else keep looking for a start token.
  323.         line = input.readline()
  324.         linecount = linecount + 1
  325.  
  326. def mkdirs_if_any(filename, verbose = 1):
  327.     """Check for existance of /'s in filename, and make directories."""
  328.  
  329.     path, file = os.path.split(filename)
  330.     if not path: return
  331.  
  332.     errno = 0
  333.     start = os.getcwd()
  334.     components = string.split(path, os.sep)
  335.     for dir in components:
  336.         if not os.path.exists(dir):
  337.             try:
  338.                 os.mkdir(dir)
  339.                 if verbose: print 'Created directory', path
  340.  
  341.             except os.error, (errno, why):
  342.                 print "Can't make directory %s: %s" % (dir, why)
  343.                 break
  344.  
  345.         try: os.chdir(dir)
  346.         except os.error, (errno, why):
  347.             print "Can't cd to directory %s: %s" % (dir, why)
  348.             break
  349.  
  350.     os.chdir(start)
  351.     return errno
  352.  
  353. def usage():
  354.     """Blah."""
  355.     die('Usage: extract.py [-V] filename [filename...]')
  356.  
  357. def main():
  358.     try: optlist, args = getopt.getopt(sys.argv[1:], 'V')
  359.     except getopt.error, why: usage()
  360.     if len(args) <= 0: usage()
  361.  
  362.     if ('-V', '') in optlist: verbose = 0
  363.     else: verbose = 1
  364.  
  365.     for filename in args:
  366.         if verbose: print 'Opening source file', filename + '...'
  367.         extract(filename, verbose)
  368.  
  369. def db(filename = 'P51-11'):
  370.     """Run this script in the python debugger."""
  371.     import pdb
  372.     sys.argv[1:] = ['-v', filename]
  373.     pdb.run('extract.main()')
  374.  
  375. def die(msg, errcode = 1):
  376.     print msg
  377.     sys.exit(errcode)
  378.  
  379. if __name__ == '__main__':
  380.     try: main()
  381.     except KeyboardInterrupt: pass
  382.  
  383.  
  384.     except getopt.error, why: usage()
  385.     if len(args) <= 0: usage()
  386.  
  387.     if ('-V', '') in optlist: verbose = 0
  388.     else: verbose = 1
  389.  
  390.     for filename in args:
  391.         if verbose: print 'Opening source file', filename + '...'
  392.         extract(filename, verbose)
  393.  
  394. def db(filename = 'P51-11'):
  395.     """Run this script in the python debugger."""
  396.     import pdb
  397.     sys.argv[1:] = [filename]
  398.     pdb.run('extract.main()')
  399.  
  400. def die(msg, errcode = 1):
  401.     print msg
  402.     sys.exit(errcode)
  403.  
  404. if __name__ == '__main__':
  405.     try: main()
  406.     except KeyboardInterrupt: pass              # No messy traceback.
  407. <-->
  408.  
  409. ----[  EOF
  410.